from rest_framework import viewsets, permissions, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from django.db.models import Count, Avg
from django.utils import timezone
from datetime import timedelta
from .models import Cluster, Node, Instance, ResourceUsage, UserAction
from .serializers import (
    ClusterSerializer, NodeSerializer, InstanceSerializer,
    ResourceUsageSerializer, UserActionSerializer
)

class ClusterViewSet(viewsets.ModelViewSet):
    queryset = Cluster.objects.all()
    serializer_class = ClusterSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['name', 'region', 'status']
    ordering_fields = ['name', 'region', 'status', 'created_at']

    @action(detail=True, methods=['get'])
    def nodes(self, request, pk=None):
        """获取集群下的所有节点"""
        cluster = self.get_object()
        nodes = Node.objects.filter(cluster=cluster)
        serializer = NodeSerializer(nodes, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['get'])
    def statistics(self, request, pk=None):
        """获取集群统计信息"""
        cluster = self.get_object()
        nodes = Node.objects.filter(cluster=cluster)
        
        # 计算资源使用率
        cpu_usage = nodes.aggregate(avg=Avg('cpu_usage'))['avg'] or 0
        memory_usage = nodes.aggregate(avg=Avg('memory_usage'))['avg'] or 0
        disk_usage = nodes.aggregate(avg=Avg('disk_usage'))['avg'] or 0
        
        return Response({
            'node_count': nodes.count(),
            'cpu_usage': cpu_usage,
            'memory_usage': memory_usage,
            'disk_usage': disk_usage
        })

class NodeViewSet(viewsets.ModelViewSet):
    queryset = Node.objects.all()
    serializer_class = NodeSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['name', 'ip_address', 'status']
    ordering_fields = ['name', 'ip_address', 'status', 'created_at']

    @action(detail=True, methods=['get'])
    def instances(self, request, pk=None):
        """获取节点下的所有实例"""
        node = self.get_object()
        instances = Instance.objects.filter(node=node)
        serializer = InstanceSerializer(instances, many=True)
        return Response(serializer.data)

    @action(detail=True, methods=['get'])
    def statistics(self, request, pk=None):
        """获取节点统计信息"""
        node = self.get_object()
        instances = Instance.objects.filter(node=node)
        
        return Response({
            'instance_count': instances.count(),
            'cpu_usage': node.cpu_usage,
            'memory_usage': node.memory_usage,
            'disk_usage': node.disk_usage
        })

class InstanceViewSet(viewsets.ModelViewSet):
    queryset = Instance.objects.all()
    serializer_class = InstanceSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['name', 'status']
    ordering_fields = ['name', 'status', 'created_at']

    @action(detail=True, methods=['get'])
    def statistics(self, request, pk=None):
        """获取实例统计信息"""
        instance = self.get_object()
        
        return Response({
            'cpu_usage': instance.cpu_usage,
            'memory_usage': instance.memory_usage,
            'disk_usage': instance.disk_usage
        })

class ResourceUsageViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = ResourceUsage.objects.all()
    serializer_class = ResourceUsageSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['resource_type']
    ordering_fields = ['timestamp']

    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取资源使用统计"""
        # 获取时间范围
        days = int(request.query_params.get('days', 7))
        start_date = timezone.now() - timedelta(days=days)
        
        # 获取资源类型
        resource_type = request.query_params.get('type', 'all')
        
        # 构建查询
        query = ResourceUsage.objects.filter(timestamp__gte=start_date)
        if resource_type != 'all':
            query = query.filter(resource_type=resource_type)
            
        # 按时间分组统计
        stats = query.values('timestamp').annotate(
            avg_cpu=Avg('cpu_usage'),
            avg_memory=Avg('memory_usage'),
            avg_disk=Avg('disk_usage')
        ).order_by('timestamp')
        
        return Response(stats)

class UserActionViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = UserAction.objects.all()
    serializer_class = UserActionSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['user__username', 'action_type', 'resource_type']
    ordering_fields = ['created_at']

    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取用户行为统计"""
        # 获取时间范围
        days = int(request.query_params.get('days', 7))
        start_date = timezone.now() - timedelta(days=days)
        
        # 按操作类型统计
        action_stats = UserAction.objects.filter(
            created_at__gte=start_date
        ).values('action_type').annotate(
            count=Count('id')
        ).order_by('-count')
        
        # 按资源类型统计
        resource_stats = UserAction.objects.filter(
            created_at__gte=start_date
        ).values('resource_type').annotate(
            count=Count('id')
        ).order_by('-count')
        
        # 按用户统计
        user_stats = UserAction.objects.filter(
            created_at__gte=start_date
        ).values('user__username').annotate(
            count=Count('id')
        ).order_by('-count')
        
        return Response({
            'action_stats': action_stats,
            'resource_stats': resource_stats,
            'user_stats': user_stats
        }) 